package com.common.app.scan

import android.os.Bundle
import android.os.PersistableBundle
import android.view.KeyEvent
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import com.common.app.databinding.ActivityScanQrCodeBinding
import com.common.base.app.activity.BaseVBActivity
import com.common.base.utils.StatusBarUtils
import com.journeyapps.barcodescanner.CaptureManager

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/26
 * <p>
 * 描述：扫描二维码
 * <p>
 * 修订历史：
 */
class ScanQrCodeActivity : BaseVBActivity<ActivityScanQrCodeBinding>(){

    private var mCaptureManager: CaptureManager? = null
    private var mScanLineAnim: Animation ?= null

    override fun getViewBinding(): ActivityScanQrCodeBinding = ActivityScanQrCodeBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewBinding.statusView)
        StatusBarUtils.setStatusBarTranslucent(this)

        //重要代码，初始化捕获
        mCaptureManager = CaptureManager(this, mViewBinding.decoratedBarcodeView)
        mCaptureManager?.initializeFromIntent(intent, savedInstanceState)
        mCaptureManager?.decode()
    }

    override fun initEvents() {
        super.initEvents()
        mViewBinding.ivBack.setOnClickListener {
            finish()
        }
    }

    private fun startScanLineAnim(){
        // 从上到下的平移动画
        mViewBinding.ivScanLine.post {
            if (mScanLineAnim == null){
                mScanLineAnim =
                    TranslateAnimation(0f, 0f, mViewBinding.ivScanLine.measuredHeight.toFloat(), mViewBinding.ivScanRect.measuredHeight.toFloat())
                mScanLineAnim?.duration = 3000 // 动画持续时间
                mScanLineAnim?.repeatCount = Animation.INFINITE // 无限循环
            }
            // 播放动画
            mViewBinding.ivScanLine.animation = mScanLineAnim
            mScanLineAnim?.startNow()
        }
    }

    private fun endScanLineAnim(){
        mScanLineAnim?.cancel()
    }

    override fun onResume() {
        super.onResume()
        mCaptureManager?.onResume()
        startScanLineAnim()
    }

    override fun onPause() {
        super.onPause()
        mCaptureManager?.onPause()
        endScanLineAnim()
    }

    override fun onDestroy() {
        super.onDestroy()
        mCaptureManager?.onDestroy()
        mScanLineAnim = null
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        mCaptureManager?.onSaveInstanceState(outState)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return mViewBinding.decoratedBarcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event)
    }

}